package com.dili.dd.gpi.controller;

import com.dili.dd.gpi.domain.GciSnapshot;
import com.dili.dd.gpi.domain.GpiSnapshot;
import com.dili.dd.gpi.dto.GciParamDto;
import com.dili.dd.gpi.dto.GpiParamDto;
import com.dili.dd.gpi.enums.ApplyType;
import com.dili.dd.gpi.enums.GPIType;
import com.dili.dd.gpi.exception.BusinessException;
import com.dili.dd.gpi.service.GciSnapshotService;
import com.dili.dd.gpi.service.GpiSnapshotService;
import com.dili.dd.gpi.util.spring.JsonView;
import com.dili.dd.gpi.util.spring.ValidatorResultUtil;
import com.google.common.base.Splitter;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * User: zhaoYuan
 * Date: 2014/9/17
 * Time: 23:55
 */
@Controller
@RequestMapping("/api")
public class ApiController {

    @Resource
    private GpiSnapshotService gpiSnapshotService;

    @Resource
    private GciSnapshotService gciSnapshotService;

    @RequestMapping(value = "/gpi",method = RequestMethod.GET)
    public ModelAndView getGpi(@Valid GpiParamDto gpiParamDto,BindingResult result){
        Map<String,Object> model = new HashMap<>();
        if(result.hasErrors()){
            model.put("success",false);
            model.put("msg", ValidatorResultUtil.getErrorMessages(result));
            return new ModelAndView(new JsonView(model));
        }

        try {
            String title = gpiParamDto.getTitle();
            List<String> splits = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(title);
            LinkedHashSet titles = new LinkedHashSet<>(splits);

            String describe = gpiParamDto.getDescribe();
            List<String> describes;
            if (describe == null) {
                describes = new LinkedList<>();
            }else{
                describes = Splitter.on("\n").omitEmptyStrings().trimResults().splitToList(describe);
            }

            List<GpiSnapshot> exists = new LinkedList<>();
            List<GpiSnapshot> news = new LinkedList<>();

            boolean apply = gpiSnapshotService.apply(gpiParamDto.getParentId(),titles, gpiParamDto.getType(),
                    gpiParamDto.getPrefix(), gpiParamDto.getSuffix(), describes, exists,news, ApplyType.API);
            Map<String,List<GpiSnapshot>> data = new HashMap<>();
            data.put("exists",exists);
            data.put("news",news);

            model.put("success",apply);
            model.put("data",data);
            model.put("msg",getMessage(apply));
            return new ModelAndView(new JsonView(model));
        } catch (BusinessException e) {
            model.put("success", false);
            model.put("msg",e.getMessage());
            return new ModelAndView(new JsonView(model));
        }
    }

    @RequestMapping(value = "/gci",method = RequestMethod.GET)
    public ModelAndView getGci(@Valid GciParamDto gciParamDto,BindingResult result){
        Map<String,Object> model = new HashMap<>();
        if(result.hasErrors()){
            model.put("success",false);
            model.put("msg", ValidatorResultUtil.getErrorMessages(result));
            return new ModelAndView(new JsonView(model));
        }

        try {
            String title = gciParamDto.getTitle();
            List<String> splits = Splitter.on(",").trimResults().splitToList(title);
            Set<String> titles = new HashSet<>(splits);

            String describe = gciParamDto.getDescribe();
            List<String> describes;
            if (describe == null) {
                describes = new LinkedList<>();
            }else{
                describes = Splitter.on("\n").trimResults().splitToList(describe);
            }

            List<GciSnapshot> exists = new LinkedList<>();
            List<GciSnapshot> news = new LinkedList<>();
            boolean apply = gciSnapshotService.apply(titles, gciParamDto.getType(),
                    gciParamDto.getPrefix(), gciParamDto.getSuffix(), describes, exists,news,ApplyType.API);
            Map<String,List<GciSnapshot>> data = new HashMap<>();
            data.put("exists",exists);
            data.put("news",news);

            model.put("success",apply);
            model.put("data",data);
            model.put("msg",getMessage(apply));
            return new ModelAndView(new JsonView(model));
        } catch (BusinessException e) {
            model.put("success", false);
            model.put("msg",e.getMessage());
            return new ModelAndView(new JsonView(model));
        }
    }

    @RequestMapping(value = "/valid",method = RequestMethod.GET)
    public ModelAndView valid(String sysGpi,String pageGpi){
        //先检查页面和系统的关系是否正确

        GpiSnapshot page = gpiSnapshotService.getByGpi(pageGpi, GPIType.PAGE);
        if(page == null){
            return new ModelAndView(new JsonView(false,"页面 GPI 不存在。"));
        }
        GpiSnapshot system = gpiSnapshotService.get(page.getParent());
        if(!sysGpi.equals(system.getGpi())){
            return new ModelAndView(new JsonView(false,"页面的gpi 和系统gpi 对应关系错误。"));
        }

        List<GpiSnapshot> gpiSnapshotList = gpiSnapshotService.findByPage(pageGpi);
        return new ModelAndView(new JsonView(true,"success",gpiSnapshotList));
    }

    private String getMessage(boolean result){
        return result ? "申请成功" : "标题已经存在，返回原有的标注信息";
    }
}